﻿using System;
using System.IO;
using System.Threading.Tasks;
using Stock.Core.Common;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.PlatformAbstractions;
using MongoDB.Driver;

namespace Stock.Core
{
	public class LogSettings
	{
		public bool Debug { get; set; }
		public bool Error { get; set; }
		public string Path { get; set; }
        public string DBType { get; set; }
	}

	public interface ILoggerService
	{
		 void Debug(LogModel content, string filePrefixName = null, string path = null);
		 void Error(LogModel content, string filePrefixName = null, string path = null);
        void Log(LogModel content, string LogType, string filePrefixName = null, string path = null);
        dynamic GetLog(DateTime? day, int? exectuedtime, string LogType="Error");
        Task RemoveAll();

	}
	public class LoggerService:ILoggerService
	{
		private LogSettings _settings;
		private IHostingEnvironment _env;


		public LoggerService(IOptions<LogSettings> op,IHostingEnvironment env)
		{
			_settings = op.Value;
			_env = env;
		}

		private  readonly object Olock = new object();
		private enum LogHelperType
		{
			debug, error
		}

        public dynamic GetLog(DateTime? day, int? exectuedtime, string LogType)
        {
            return new { message = "file can't get" };
        }

        public async Task RemoveAll()
		{
		}
		/// <summary>
		/// 记录调试日志
		/// </summary>
		/// <Param name="content">内容。如需换行可使用：\r\n</Param>
		/// <Param name="filePrefixName"></Param>
		/// <Param name="path">格式：D:\\File\\Logs\\</Param>
        public  void Debug(LogModel MonLog, string filePrefixName = null, string path = null)
		{
            string content = MonLog.GetLoginfo();
			Write(LogHelperType.debug, content, filePrefixName, path);
		}

		/// <summary>
		/// 记录调试日志
		/// </summary>
		/// <Param name="content">内容。如需换行可使用：\r\n</Param>
		/// <Param name="filePrefixName"></Param>
		/// <Param name="path">格式：D:\\File\\Logs\\</Param>
		public void Log(LogModel MonLog, string LogType, string filePrefixName = null, string path = null)
		{
			string content = MonLog.GetLoginfo();
			Write(LogHelperType.debug, content, filePrefixName, path);
		}

		/// <summary>
		/// 记录错误日志
		/// </summary>
		/// <Param name="content">内容。如需换行可使用：\r\n</Param>
		/// <Param name="filePrefixName"></Param>
		/// <Param name="path">格式：D:\\File\\Logs\\</Param>
        public  void Error(LogModel MonLog, string filePrefixName = null, string path = null)
		{
			string content = $"请求【{MonLog.ControllerName}】的【{MonLog.ActionName}】" +
                $"产生异常：Action参数:{MonLog.ActionParams}, " +
							  $"Http请求头:{MonLog.HttpRequestHeaders}," +
							  $"客户端IP:," +
							  $"HttpMethod:{MonLog.HttpMethod}," +
							  $"Message{MonLog.Message}, " +
				$"StackTrace{MonLog.StackTrace}";
			Write(LogHelperType.error, content, filePrefixName, path);
		}
		/// <summary>
		/// filePrefixName是文件名前缀，最好用中文，方便在程序Logs文件下查看。
		/// </summary>
		/// <Param name="content">内容。如需换行可使用：\r\n</Param>
		/// <Param name="filePrefixName"></Param>
		/// <Param name="path"></Param>
		/// <Param name="logtype"></Param>
		private  void Write(LogHelperType logtype, string content, string filePrefixName = null, string path = null)
		{
			lock (Olock)
			{
				try
				{
					if (logtype == LogHelperType.debug)
					{
						if (!_settings.Debug)
						{
							return;
						}
					}
					else
					{
						if (!_settings.Error)
						{
							return;
						}
					}
					#region 日志文件
					var fileName = filePrefixName + DateTime.Now.ToString("yyyyMMdd") + logtype.ToString() + ".txt";
					if (string.IsNullOrWhiteSpace(path))
					{
						var dosPath = _settings.Path;
						if (string.IsNullOrWhiteSpace(dosPath))
						{
							path = _env.ContentRootPath + "//Logs//" + fileName;
						}
						else
						{
							path = dosPath + fileName;
						}
					}
					else
					{
						path += fileName;
					}
					var di = new DirectoryInfo(path.Replace(fileName, ""));
					if (!di.Exists)
					{
						di.Create();
					}
					//判断文件大小，需要新开文件
					using (var fs = new FileStream(path, FileMode.Append, FileAccess.Write))
					{
						var sw = new StreamWriter(fs);
						sw.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
						sw.WriteLine();
						sw.Write(content);
						sw.WriteLine();
						sw.Write("-----------------------------------------------------------------------------");
						sw.WriteLine();
						sw.Flush();
					}
					#endregion
				}
				catch
				{
				}
			}
		}
	}
}
